const router = require('express').Router()
const runtimeLogger = require('../../log4js')()
const Service = require('../../tsp/service')

router.post('/', (req, res) => {
  runtimeLogger.info(`开始请求 ${req.originalUrl}, body: ${JSON.stringify(req.body)}`)
  /* eslint-disable object-curly-spacing */
  const { body: { header, payload } } = req

  checkNamespace(header)

  const Instance = new Service({ header, payload })
  Instance.run().then(data => {
    res.send(data)
  })
})

/**
 * check namespace valid
 * @param header
 */
function checkNamespace(header) {
  const SupportedNS = ['AcceptGrant', 'CancelGrant', 'DeviceDiscovery', 'DeviceSnapshot', 'SubscribeDevice', 'UnsubscribeDevice', 'DeviceCommand']
  const { namespace } = header
  if (!SupportedNS.includes(namespace)) {
    throw new Error(`暂不支持namespace: ${namespace}. 请更改为: ${SupportedNS.toString()}`)
  }
}

module.exports = router
